from django.shortcuts import render
import logging
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
logging = logging.getLogger('django')

from orders.models import Order
from payments.models import PaymentRecord
from utils.snowflake import generate_id
from payments.wxpay import WxPayClient
# Create your views here.


# 对接微信的下单接口
class WxPayOrderApiView(APIView):

    # 必登录
    permission_classes = [IsAuthenticated]
    def post(self,request):

        # 接受参数：
        # 订单号
        order_number = request.data.get('order_number')

        if not order_number:
            logging.error('订单号不能为空')
            return Response({
                'code':0,
                'message':'订单号不能为空'
            })

        # 判断订单的状态是否是未支付，如果是未支付才能进行下单
        try:
            order = Order.objects.get(order_number=order_number,user=request.user)
            # 记得一定要判断user，因为是这个人的购物车里有没有状态为0的数据
            if order.order_status != 0:
                return Response({
                    'code':0,
                    'message':'订单状态不正确'
                })


            # 生成支付订单号提出来，因为调用雪花算法
            pay_order_number=str(generate_id())
            # 如果以上条件都满足，则可以进行生成订单记录
            pay_record = PaymentRecord.objects.create(
                order=order,
                order_number=order_number,
                pay_order_number=pay_order_number,
                pay_method=2,
                pay_amount=order.real_price,   # 实际付款金额
                pay_status=0,
            )

            # 实例化微信类：准备对结尾新街口
            client = WxPayClient()
            # 调用微信下单接口:native

            # def create_order(self, order_number, total_fee, description):
            #     """创建Native支付订单
            #     :param order_number: 商户订单号
            #     :param total_fee: 订单金额（单位：分）
            #     :param description: 商品描述
            #     :return: 支付二维码链接
            #     """

            # 调用这个生成微信支付订单的方法：需要传参数
            # 把参数意义实现：
            order_number=pay_order_number  # 你传给微信的一定是支付订单号！！
            total_fee=int(float(order.real_price)*100)   # 默认单位是分，所以要乘以100
            description=f"码镜空间：{order_number}"
            # 用微信类实例调用生成订单方法并传入参数-->会返回给你一个二维码支付连接：code_url
            code_url = client.create_order(order_number,total_fee, description)

            if not code_url:
                return Response({
                    'code':0,
                    'message':'下单失败'
                })

            # 相反的话就是下单成功，你需要修改订单大表的状态为已支付，支付记录表也要修改
            # 更新支付记录
            pay_record.pay_remark = "发起微信支付成功"
            pay_record.save()

            # 修改order订单支付方式
            order.pay_method = 2
            order.save()

            # 构建返回结果
            results = {
                # 这里其实返回的结果就是实付、总金额、支付二维码链接和支付唯一订单
                'order_number':order_number,
                'total_fee':total_fee,
                'pay_url':code_url,
                'pay_order_number':pay_order_number,
            }

            return Response({
                'code':1,
                'errmsg':'下单成功',
                'data':results
            })


        except Exception as e:
            logging.error(f"微信下单异常：{str(e)}")
            return Response({"code": 0, "message": str(e)})





